package com.song.jd.shiro.authority;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.aspectj.weaver.Iterators.Getter;

import com.song.jd.shiro.bean.User;
import com.song.jd.shiro.service.UserService;

public class UserRealm  extends AuthorizingRealm{
	
	@Resource
	private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String username = (String) principalCollection.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(null);
		authorizationInfo.setStringPermissions(null);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		String username = (String) token.getPrincipal();
		User user = userService.findByUsername(username);
		if(null == user)
		{
			throw new UnknownAccountException();
		}
		SimpleAuthenticationInfo  authenticationInfo = 
				new SimpleAuthenticationInfo(
				user.getUserName(),user.getPassWord() , ByteSource.Util.bytes(user.getCredentialsSalt()),getName());
		
		return authenticationInfo;
	}

}
